//
//  HttpManager.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "HttpManager.h"

#import <SVProgressHUD.h>

@implementation HttpManager

static HttpManager *http = nil;
#pragma mark -- 单例方法
+ (HttpManager *)shareHttpManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        http = [[HttpManager alloc]init];
    });
    return http;
}

#pragma mark -- GET请求(请求体为json格式)
- (void)getJsonWithUrl:(NSString *)url parameter:(NSString *)json hiddenHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    //如果有错误提示将这一句注释解开
    //[self.manager.requestSerializer requestWithMethod:@"GET" URLString:url parameters:json error:nil];
    /*如果要在header里面传递请求参数将此处注释解开*/
    //获取项目中的token
//    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
//    NSString *tokenStr = [QJUserInfo getToken] ? [QJUserInfo getToken] : @"";
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    [dict setValue:tokenStr forKey:@"token"];
//    [dict setValue:@"iOS" forKey:@"apptype"];
//    if (dict != nil) {
//        for (NSString *httpHeaderField in dict.allKeys) {
//            NSString *value = dict[httpHeaderField];
//            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
//        }
//        
//    }
//    self.manager.requestSerializer = requestSerializer;
    /**/
    
    [self.manager GET:url parameters:json progress:^(NSProgress * _Nonnull downloadProgress) {
        //请求进度
        KMyLog(@"已请求：%lld,总请求：%lld", downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功
        [SVProgressHUD dismiss];
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            //数据有效
            success(operation, response);
            
        } failure:^(NSURLSessionDataTask *operation, id response) {
            //数据无效提示
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        [SVProgressHUD dismiss];
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
    
}
#pragma mark -- GET请求(请求体为dict格式)
-(void)getDictWithUrl:(NSString *)url parameter:(NSDictionary *)dict hiddenHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    
    /*如果要在header里面传递请求参数将此处注释解开*/
    //获取项目中的token
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    NSString *tokenStr = [QJUserInfo getToken] ? [QJUserInfo getToken] : @"";
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:tokenStr forKey:@"XX-Token"];
    [dic setValue:@"test" forKey:@"XX-Device-Type"];
    if (dic != nil) {
        for (NSString *httpHeaderField in dic.allKeys) {
            NSString *value = dic[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
        
    }
    self.manager.requestSerializer = requestSerializer;
    /**/
    
    [self.manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        //请求进度
        KMyLog(@"已请求：%lld,总请求：%lld", downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功
        [SVProgressHUD dismiss];
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            //数据有效
            success(operation, response);
            
        } failure:^(NSURLSessionDataTask *operation, id response) {
            //数据无效提示
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        [SVProgressHUD dismiss];
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
}
#pragma mark -- POST请求(请求体为json格式)
-(void)postJsonWithUrl:(NSString *)url parameter:(NSString *)json hiddenHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    //如果报错讲这句的注释解开
    //[self.manager.requestSerializer requestWithMethod:@"POST" URLString:url parameters:json error:nil];
    /*如果要在header里面传递请求参数将此处注释解开*/
    //获取项目中的token
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    NSString *tokenStr = [QJUserInfo getToken] ? [QJUserInfo getToken] : @"";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:tokenStr forKey:@"XX-Token"];
    [dict setValue:@"test" forKey:@"XX-Device-Type"];
    if (dict != nil) {
        for (NSString *httpHeaderField in dict.allKeys) {
            NSString *value = dict[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }

    }
    self.manager.requestSerializer = requestSerializer;
    /**/
    
    [self.manager POST:url parameters:json progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
    //上传文件用的post方法
    //    [self.manager POST:url parameters:json constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //    } progress:^(NSProgress * _Nonnull uploadProgress) {
    //
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //    }];
}
#pragma mark -- POST请求(请求体为dict格式)
- (void)postDictWithUrl:(NSString *)url parameter:(NSDictionary *)dict hiddenHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    /*如果要在header里面传递请求参数将此处注释解开*/
    //获取项目中的token
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    NSString *tokenStr = [QJUserInfo getToken] ? [QJUserInfo getToken] : @"";
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:tokenStr forKey:@"XX-Token"];
    [dic setValue:@"test" forKey:@"XX-Device-Type"];
    if (dic != nil) {
        for (NSString *httpHeaderField in dic.allKeys) {
            NSString *value = dic[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
        
    }
    self.manager.requestSerializer = requestSerializer;
    /**/
    [self.manager POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            if ([response[@"code"] intValue] == 500 && [response[@"msg"] isEqualToString:@"未发现店铺"]) {
                
            }else {
                [self tipWithTitle:response];
            }
            
            failure(operation, response);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
    
}
#pragma mark -- 图片上传不带有图片的名字
-(void)postImageWithUrl:(NSString *)url parameter:(NSDictionary *)dict hiddeHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    [self.manager POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
}
#pragma mark -- 图片上传带有图片文件
- (void)postImagefileWithUrl:(NSString *)url parameter:(NSDictionary *)dict withImageFile:(UIImage *)image hiddenHUD:(BOOL)hiden HUDTitle:(NSString *)title success:(QJNetworkManagerBlock)success failure:(QJNetworkManagerBlock)failure{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    if (hiden) {
        [SVProgressHUD showWithStatus:title];
    }
    
    // 头部信息
    [self setHeaderInformation];
    /**/
    NSLog(@"图片 url = %@", url);
    NSLog(@"图片 dict = %@", dict);
    //  方法二:数据流上传
    NSString *imgUrl = [NSString stringWithFormat:@"%@%@",kApiPrefix,url];
    [self.manager POST:imgUrl parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        // 一般用时间拼接
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];

        //上传图片
        NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
        // imageData:要上传的文件
        // name:这个参数是后台取文件参数的时候用的名字，如果没有的话就传空字符串
        // fileName:文件上传的名字，可以随便取，但是不要重名，所以一般是用拼接当前时间的方式作为文件名
        // @"file.jpg"
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        NSLog(@"formData = %@", formData);

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSLog(@"responseObject = %@", responseObject);
        [self requestResponse:responseObject operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        NSLog(@"上传错误error = %@", error);
        [self requestResponse:task.response operation:task success:^(NSURLSessionDataTask *operation, id response) {
            success(operation, response);
        } failure:^(NSURLSessionDataTask *operation, id response) {
            [self tipWithTitle:response];
            failure(operation, response);
        }];
    }];
    
}

// 如果后台没有给出提示, 这里前端给出提示
- (void)tipWithTitle:(id)response {  // QJNetworkManager 传过来的response 一定要是字典类型
    
    NSString *title = [response objectForKey:@"msg"];
    if (title.length) {
        [MBPHUD showAlertWithTitle:title];
    }else {
        [MBPHUD showAlertWithTitle:@"网络异常, 请稍后再试!"];
    }
}

- (void)setHeaderInformation {
    // 头部信息
    // 时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    // token
    UserInfoModel *model = [QJUserInfo getCurrentUser];
    NSString *tokenStr = model.token ? model.token : @"";
    NSLog(@"tokenStr = %@", tokenStr);
    NSNumber *lastlogin = model.last_login ? model.last_login : 0;
    NSString *lastloginStr = [NSString stringWithFormat:@"%@", lastlogin];
    // 设置头部信息
    AFHTTPRequestSerializer *requestSerializer =  [AFHTTPRequestSerializer serializer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:tokenStr forKey:@"token"];       // 用户token
    [dic setObject:lastloginStr forKey:@"lastlogin"];// 最后登录时间
    [dic setObject:@"" forKey:@"signalture"];       // 签名验证字符串 （加密规则待定）
    [dic setObject:@"ios" forKey:@"devicetype"];    // 设备号 （android，ios等）
    [dic setObject:timeString forKey:@"timestamp"]; // 时间戳
    
    if (dic != nil) {
        for (NSString *httpHeaderField in dic.allKeys) {
            NSString *value = dic[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    self.manager.requestSerializer = requestSerializer;
//    [WWNetworkHelper setAFHTTPRequestSerializer:requestSerializer];
}
@end
